package com.atung.parking.controller;

import com.atung.parking.config.result.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/api/file")
@Api(tags = "统一文件管理")
public class FileUploadController {

    //    private final String uploadDirPath = "http://123.57.224.37/uploadDir/";
    private final String uploadDirPath = "https://www.bodou.top/uploadDir/";

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public ApiResult uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ApiResult.fail("File is empty");
        }

        try {
            // 定义上传目录的路径
            String uploadDir = "/usr/local/java/uploadDir/";
            Path uploadPath = Paths.get(uploadDir);

            // 创建目录（如果不存在）
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 获取文件原始后缀
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 生成文件名（时间戳 + 后缀）
            String filename = System.currentTimeMillis() + fileExtension;

            // 保存文件
            Path filePath = uploadPath.resolve(filename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回文件的绝对路径
            return ApiResult.ok(uploadDirPath + filename);

        } catch (IOException e) {
            e.printStackTrace();
            return ApiResult.fail("File upload failed: " + e.getMessage());
        }
    }

}
